package com.example.demo.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

//定时器
@EnableScheduling
@Component
public class TestSenderController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //向redis消息队列index通道发布消息
    @Scheduled(fixedRate = 3000)
    public void sendMessage(){
        stringRedisTemplate.convertAndSend("index",String.valueOf(Math.random()));
    }

    //向redis消息队列topic通道发布消息
    @Scheduled(fixedRate = 2000)
    public void sendMessageToTopic(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", RandomUtil.randomColor());
        stringRedisTemplate.convertAndSend("topic",jsonObject.toJSONString());
    }

    //向redis消息队列topic:newMsg通道发布消息
    @Scheduled(fixedRate = 2000)
    public void sendMessageToNewMsg(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name",RandomUtil.randomString(10));
        stringRedisTemplate.convertAndSend("topic:newMsg",jsonObject.toJSONString());
    }


}
